package db4oToOracle.obj1test;


import com.googlecode.datawander.connectors.Db4oUtil;
import com.googlecode.datawander.connectors.OracleConnector;
import java.sql.SQLException;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MarcinStachniuk
 */
public class Task extends SuperTask {

    private String name;

    public static void saveAllRecords(Task [] tasks) throws Exception {
        if(tasks != null) {
            java.sql.Connection conn = OracleConnector.getConnection();
            for(Task o : tasks) {
                o.saveRecord(conn);
            }
        }
    }

    private void saveRecord(java.sql.Connection conn) throws java.sql.SQLException {
        String sql = "insert into \"Task\" (\"GENERATED_ID\", \"name\", \"GEN_Task_AppUser\", \"SuperTask_ID_INHERITANCE\") " +
                "values (?,?,?,?)";
        java.sql.PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setLong(1, getIdFromDb4o());
        stmt.setString(2, name);

        long id = 0;
        com.db4o.ObjectSet<AppUser> mySet = AppUser.getAppUserByTaskFromDb4o(this);  // 1:N
        if(mySet.size() != 0) {
            if(mySet.size() == 1) {     // OK
                AppUser temp = mySet.get(0);
                id = temp.getIdFromDb4o();
                stmt.setLong(3, temp.getIdFromDb4o());
            } else {
                System.out.println("Błąd - powinno znales jedna referencje");
            }
        } else {        // nie ma, moze nie byc
            stmt.setNull(3, java.sql.Types.NUMERIC);
        }

        stmt.setLong(4, super.getIdFromDb4o());

        stmt.executeUpdate();
        System.out.println("Zapisano Task id: "+getIdFromDb4o() + " name: " +
                name + " id AppUser "+ id + " super "+super.getIdFromDb4o());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * Pobiera id z db4o. Zakładam ze wynik bedzie inny niz zero, w przeciwnym
     * wypadku bedzie to obiekt ktorego nie bylo w db4o
     * @return
     */
    public long getIdFromDb4o() {
        com.db4o.ObjectContainer db = Db4oUtil.getObjectContainer();
        long id = db.ext().getID(this);
        return id;
    }
}
